package jgo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.sun.net.httpserver.HttpExchange;
import static jgo.Http.*;

public class Context {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private Map<String, String> params = new HashMap<>();
	private Map<String, String> headers = new HashMap<>();
	private int statusCode = 200;
	private String responseBody;
	private HttpExchange exchange;
	public boolean responseSent = false;
	public boolean handled = false;

	public Context() {
	}

	public Context(HttpExchange exchange) {
		this.exchange = exchange;
	}

	public String getMethod() {
		logger.trace("Getting request method");
		return exchange.getRequestMethod();
	}

	public String getPath() {
		logger.trace("Getting request path");
		return exchange.getRequestURI().getPath();
	}

	public Context status(int status) {
		logger.debug("Setting response status: {}", status);
		this.statusCode = status;
		return this;
	}

	public Context string(String string) {
		logger.debug("Setting response body: {}", string);
		// 设置响应体的代码

		try {
			byte[] responseBytes = string.getBytes(StandardCharsets.UTF_8);
			exchange.getResponseHeaders().set("Content-Type", "application/json");
			exchange.sendResponseHeaders(statusCode, responseBytes.length);
			try (OutputStream os = exchange.getResponseBody()) {
				os.write(responseBytes);
			}
		} catch (IOException e) {
			throw new RuntimeException("Error sending JSON response", e);
		}
		return this;

	}

	public Context json(Object obj) {
		logger.debug(" Setting response JSON: {}", obj);
		// 设置JSON响应的代码

		try {
			String jsonResponse = JSON.toJSONString(obj);
			byte[] responseBytes = jsonResponse.getBytes(StandardCharsets.UTF_8);
			exchange.getResponseHeaders().set("Content-Type", "application/json");
			exchange.sendResponseHeaders(statusCode, responseBytes.length);
			try (OutputStream os = exchange.getResponseBody()) {
				os.write(responseBytes);
			}
			responseSent = true;
		} catch (IOException e) {
			throw new RuntimeException("Error sending JSON response", e);
		}
		return this;
	
	}

	public String body() {
		logger.trace("Getting request body");
		// 这里需要实现从HttpExchange中读取请求体的逻辑
		// 为简化,这里返回空字符串,实际应该读取输入流
		return "";
	}

	public String getHeader(String name) {
		logger.trace("Getting header: {}", name);
		return exchange.getRequestHeaders().getFirst(name);
	}

	public Context param(String name, String value) {
		params.put(name, value);
		return this;
	}

	public String param(String name) {
		return params.get(name);
	}

	public Context header(String name, String value) {
		headers.put(name, value);
		return this;
	}

	public String header(String name) {
		return headers.get(name);
	}

	public Context redirect(String url) {
		logger.debug("Redirecting to: {}", url);
		statusCode = FOUND;
		header("Location", url);
		return this;
	}

	public Context contentType(String type) {
		logger.debug("Setting content type: {}", type);
		header("Content-Type", type);
		return this;
	}

	// 保留这个完整的实现
	public Context body(byte[] data) {
		logger.debug("Setting response body with {} bytes", data.length);
		try {
			exchange.getResponseHeaders().set("Content-Length", String.valueOf(data.length));
			exchange.sendResponseHeaders(statusCode, data.length);
			try (OutputStream os = exchange.getResponseBody()) {
				os.write(data);
			}
			responseSent = true;
		} catch (IOException e) {
			throw new RuntimeException("Error sending response body", e);
		}
		return this;
	}

	public void setHandled(boolean handled) {
		this.handled = handled;
	}

	public boolean isHandled() {
		return handled;
	}

	public String queryParam(String name) {
		// 实现获取查询参数的逻辑
		String query = exchange.getRequestURI().getQuery();
		if (query != null) {
			for (String param : query.split("&")) {
				String[] pair = param.split("=");
				if (pair.length > 1 && pair[0].equals(name)) {
					return pair[1];
				}
			}
		}
		return null;
	}

	public String formData(String name) {
		// 实现获取表单数据的逻辑
		// 注意：这个实现假设表单数据是 URL 编码的
		String body = this.body();
		for (String param : body.split("&")) {
			String[] pair = param.split("=");
			if (pair.length > 1 && pair[0].equals(name)) {
				return pair[1];
			}
		}
		return null;
	}

	public String pathParam(String name) {
		return params.get(name);
	}

}
